/**
 * Copyright 2012 Brigham Young University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package edu.byu.nlp.cluster;

import com.google.common.base.Preconditions;

import edu.byu.nlp.cluster.em.ClusteringAndPredictiveModels;
import edu.byu.nlp.cluster.em.ExpectationMaximization;
import edu.byu.nlp.cluster.em.ExpectationMaximization.ParameterPair;
import edu.byu.nlp.cluster.em.ParameterInitializer;
import edu.byu.nlp.math.optimize.ValueAndObject;

/**
 * An EM-based Clusterer (or related, e.g., variational Bayes) for MAP estimation of the parameters of a mixture
 * model.
 * 
 * @author rah67
 *
 */
public class EMClusterer<P> implements ProbabilisticClusterer {

	private final ExpectationMaximization em;
	private final ParameterInitializer<P> initializer;
	private final EMAble<P> emAble;
	
	/**
	 * Instantiates an EM-based clusterer. 
	 */
	public EMClusterer(ExpectationMaximization em, ParameterInitializer<P> initializer, EMAble<P> emAble) {
		Preconditions.checkNotNull(em);
		Preconditions.checkNotNull(initializer);
		Preconditions.checkNotNull(emAble);
		
		this.em = em;
		this.initializer = initializer;
		this.emAble = emAble;
	}

	@Override
	public ProbabilisticClustering cluster(Dataset data, int numClusters) {
		P initialParams = initializer.initialize(data, numClusters);
		// Pre-allocate space for the next parameters; (TODO: clone() or secondary initializer would be preferable)
		P nextParams = initializer.initialize(data, numClusters);
		ParameterPair<P> paramPair = new ParameterPair<P>(initialParams, nextParams);
		ValueAndObject<P> parametersAndLowerbound =
				em.em(data, emAble.newExpectableFor(data, numClusters), paramPair);
		P params = parametersAndLowerbound.getObject();

		// Build clustering and predictive models, and cluster!
		ClusteringAndPredictiveModels models = emAble.newModelsFrom(params);
		return BasicProbabilisticClustering.newClustering(data, numClusters, models.getClusteringModel(),
				models.getPredictiveModel(), parametersAndLowerbound.getValue());
	}

}
